import { message, Form, Input, Breadcrumb, Space, Button, Radio } from 'antd';
import { RichTextEdit } from '@/components/RichText'
import styles from './style.less';
import { useState, useEffect } from 'react';
import { Prompt } from 'react-router-dom';
import { saveArticle, getById, updateArticle } from '@/services/doc/article'
import { PROJECT_ACL } from '@/consts/doc'
import EnterpriseUserSelect from '@/components/EnterpriseUserSelect'


const ArticleEdit = (props) => {

    const {
        docData,
        onSaveSuccess,
        projectId,
        onSaveDraftSuccess,
    } = props;
    const [form] = Form.useForm();
    const [saveEnable, setSaveEnable] = useState(false);
    const [dirRoutes, setDirRoutes] = useState([]);
    const [changedValues, setChangedValues] = useState([])

    const [defaultDocValues, setDefaultDocValues] = useState({
        // acl:"ReadPublic"
    })

    useEffect(() => {
        form.resetFields()
    }, [defaultDocValues])

    useEffect(() => {
        if (docData) {
            // console.log(docData)
            if (docData.docId) {
                getById(projectId, docData.docId)
                    .then(result => {
                        let aclUserList = result?.data?.aclUserList || [];
                        setDefaultDocValues({
                            ...result?.data,
                            aclUserIds: aclUserList.map(user => user.id)
                        })
                        setChangedValues({
                            ...result?.data,
                            aclUserIds: aclUserList.map(user => user.id)
                        })
                        let routes = []
                        if (result?.data?.dirRoute) {
                            result?.data?.dirRoute.forEach((dir) => {
                                routes.push({
                                    // path: dir.id,
                                    breadcrumbName: dir.name
                                })
                            })
                        }
                        setDirRoutes(routes);
                    })
            } else {
                let routes = []
                if (docData.dirRoutes) {
                    docData.dirRoutes.forEach((dir) => {
                        routes.push({
                            // path: dir.id,
                            breadcrumbName: dir.title
                        })
                    })
                }
                setDirRoutes(routes);
                setDefaultDocValues({
                    acl: "ReadPublic"
                })
            }

        }
    }, [docData])


    const saveDoc = async () => {
        const values = await form.validateFields();
        console.log(values)
        if (docData.docId) {
            updateArticle(projectId, docData.docId, {
                ...values,
            }).then((result) => {
                setSaveEnable(false)
                if (onSaveSuccess) {
                    onSaveSuccess(result?.data)
                }
            })
        } else {
            saveArticle(projectId, {
                ...values,
                dirId: docData.dir?.id,
            }).then((result) => {
                setSaveEnable(false)
                if (onSaveSuccess) {
                    onSaveSuccess(result?.data)
                }
            })
        }
    }


    const onValueChange = (values) => {
        setChangedValues({
            ...changedValues,
            ...values
        })
        if (values?.content?.text === "<p></p>") {
            setSaveEnable(false)
            return;
        }
        setSaveEnable(true)
    }

    return (<div className={styles.editContent}>
        <Prompt message={"文章还未保存，是否放弃编辑！"} when={saveEnable} />
        <div className={styles.header}>
            <Breadcrumb className={styles.dirRoute} routes={dirRoutes}>
            </Breadcrumb>
            <Space size={4}>
                <Button key="saveDraft">保存为草稿</Button>
                <Button key="publish" disabled={!saveEnable} type="primary" onClick={saveDoc}>保存</Button>
            </Space>
        </div>
        <Form form={form} onValuesChange={onValueChange} initialValues={defaultDocValues}>
            <Form.Item className={styles.titleFormItem}
                rules={[{
                    required: true,
                    message: '请输入标题'
                },
                {
                    type: "string",
                    max: 20,
                    min: 3,
                    message: '名字为3~50个字符'
                }]}
                name="name">
                <Input placeholder="请输入标题" className={styles.title} bordered={false}></Input>
            </Form.Item>
            <Form.Item name="abstractTitle" className={styles.abstractFormItem}>
                <Input.TextArea placeholder="请输入摘要"
                    bordered={false}
                    rules={[
                        {
                            type: "string",
                            max: 200,
                            min: 0,
                            message: '名字为0~200个字符'
                        }]}
                >
                </Input.TextArea>
            </Form.Item>
            <Form.Item name="content">
                <RichTextEdit
                    size="large"
                    showMoreControl={false}
                    showFormButton={false}
                    className={styles.contentEdit}></RichTextEdit>
            </Form.Item>
            <Form.Item name="acl" label="访问权限">
                <Radio.Group>
                    <Radio value={PROJECT_ACL.ReadPublic}>公共读</Radio>
                    <Radio value={PROJECT_ACL.WritePerson}>指定可编辑</Radio>
                    <Radio value={PROJECT_ACL.WritePublic}>开放</Radio>
                </Radio.Group>
            </Form.Item>
            {changedValues?.acl === PROJECT_ACL.WritePerson &&
                <Form.Item name="aclUserIds" label="指定人员">
                    <EnterpriseUserSelect ismultiple={true} projectId={projectId}></EnterpriseUserSelect>
                </Form.Item>
            }

        </Form>
    </div>)
}

export default ArticleEdit;